//
//  WBMainViewController.swift
//  WinsonWeibo
//
//  Created by Administrator on 2017/4/14.
//  Copyright © 2017年 Winson. All rights reserved.
//

import UIKit
import SVProgressHUD

/// 主控制器
class WBMainViewController: UITabBarController {

    /// 定义一个时钟变量 监听新微博条数
    fileprivate var timer: Timer?


    override func viewDidLoad() {

        super.viewDidLoad()

        setupChildControllers()
        setupComposeButton()
        setupTimer()

        // 设置 新特性view 或 欢迎view
        setupNewFeatureAndWelcomeUI()

        delegate = self

        // 注册接受通知
        NotificationCenter.default.addObserver(
            self,
            selector: #selector(notificationLogin(n:)),
            name: NSNotification.Name(rawValue: WeiboUserShouldLoginNotification),
            object: nil)
    }

    deinit {
        // 销毁时钟
        timer?.invalidate()
        // 移除通知
        NotificationCenter.default.removeObserver(self)
    }
    // MARK: - 按钮监听方法
    func notificationLogin(n: Notification) {

        // toekn 过期
        var when = DispatchTime.now()

        if n.object != nil {

            // 设置SVProgressHUD的显示样式
            SVProgressHUD.setDefaultMaskType(SVProgressHUDMaskType.gradient)
            SVProgressHUD.showInfo(withStatus: "登录已经超时，请重新登录")
            when = DispatchTime.now() + 1.5
        }
        DispatchQueue.main.asyncAfter(deadline: when, execute: {

            // 恢复SVProgressHUD的样式
            SVProgressHUD.setDefaultMaskType(SVProgressHUDMaskType.clear)

            print("通知用户登录\(n)")
            self.present(UINavigationController(rootViewController: WBOAuthViewController()), animated: true, completion: nil)
        })
    }
    // MARK: - 私有控件
    lazy var composeImageButton: UIButton = UIButton.cz_imageButton("tabbar_compose_icon_add", backgroundImageName: "tabbar_compose_button")

    /// 设置设备支持的方法（竖屏）在main设置后， 它和它的子控制器都将遵循
    /// 如果要横屏 则需要使用 modal一个控制器来设置
    override var supportedInterfaceOrientations: UIInterfaceOrientationMask {

        return UIInterfaceOrientationMask.portrait
    }
}

// MARK: - 设置 新特性view 或 welcome view
extension WBMainViewController {

    fileprivate func setupNewFeatureAndWelcomeUI() {

        // 1. 判断是否 登录， 登录就设置， 没有登录就return
        if !WBNetworkManager.shared.userLogon {
            return
        }
        // 2. 判断是否时新版本
        let v = isNewFeature ? WBNewFeatureView.newFeatureView() : WBWelComeView.welcomeView()

        v.frame = view.bounds
        // 3. 显示view
        view.addSubview(v)

    }

    /// extension 中可以有计算性属性，因为计算性属性不占内存空间， 而类的init方法时为属性分配内存空间
    private var isNewFeature: Bool {
        // 判断新版本逻辑
        // 1. 取当前的版本
        let currentVersion = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? ""

        // 2. 取保存在 “Document（iTunes会备份，升级到新版本后依然存在）” 中的 版本号
        let path: String = ("version" as NSString).cz_appendDocumentDir()
        let sanboxVersion = (try? String(contentsOfFile: path)) ?? ""
        // 3. 保存当前版本号 到 沙盒 中
        try? currentVersion.write(toFile: path, atomically: true, encoding: String.Encoding.utf8)
        // 4. 返回比较的结果 “二个版本号是否一致”
        return currentVersion != sanboxVersion
    }
}

// MARK: - UITabBarControllerDelegate
extension WBMainViewController: UITabBarControllerDelegate {

    func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {

        // 1. 取出当前viewcongtroller 在tabbarcontroller的子控制器数组中的位置
        let idx = viewControllers?.index(of: viewController)

        // 2. 判断是否重复点击了 tabbar 上的 home 此按钮
        if selectedIndex == 0 && selectedIndex == idx {
            // 3. 取出此时的导航控制器
            let nav = viewControllers?[selectedIndex] as! WBNavigationController
            // 4. 取出栈底的控制器
            let vc = nav.viewControllers[0] as! WBHomeViewController

            // 5. vc 的tableview滚动到顶部
            vc.tableView?.setContentOffset(CGPoint(x: 0, y: -64), animated: true)

            // 6. 延迟刷新tableView数据
            DispatchQueue.global().asyncAfter(deadline: DispatchTime.now() + 1, execute: { 

                vc.loadData()
            })
            // 清除tabbarIntem的badgeNumber
            vc.tabBarItem.badgeValue = nil
            UIApplication.shared.applicationIconBadgeNumber = 0
        }
        return !viewController .isMember(of: UIViewController.self)
    }
}

// MARK: -  设置获取新微博条数的时钟
extension WBMainViewController {

    fileprivate func setupTimer() {

        timer = Timer.scheduledTimer(timeInterval: 5, target: self, selector: #selector(supdateTimer), userInfo: nil, repeats: true)
    }
    /// 更新时钟
    @objc fileprivate func supdateTimer() {

        if !WBNetworkManager.shared.userLogon {
            return
        }
        WBNetworkManager.shared.unreadCount { (count) in

            // 取home的tabbarButtonItem
            self.tabBar.items?[0].badgeValue = count == 0 ? nil : "\(count)"

            // 设置app的badge, iOS8.0之后 要用户授权才能显示
            UIApplication.shared.applicationIconBadgeNumber = count
        }
    }
}

// extension 类似 OC 中的 分类， 在Swift中还可以用来切分代码块
// 可以吧相近功能的函数， 放在一个extension中
// 便于代码维护
// 注意： 和 OC 的分类一样， extension 中不能定义属性

// MARK： - 设置界面
private extension WBMainViewController {

    // 设置撰写按钮
    func setupComposeButton() {

        tabBar.addSubview(composeImageButton)

        // 计算按钮的宽度
        let count = CGFloat(childViewControllers.count)

        // 将向内缩进的宽度减少， 能够让按钮的宽度变大，盖住容错点，防止穿帮
        let w = tabBar.bounds.width/count

        // CGRectInset 正数向内缩进， 附属向外扩展
        composeImageButton.frame = tabBar.bounds.insetBy(dx: 2 * w, dy: 0)

        // MARK: - 按钮监听方法
        // composeImageButton.addTarget(self, action: #selector(composeStauts), for: UIControlEvents.touchUpInside)
    }

    // 设置所有子控制器
    func setupChildControllers() {

        // 从沙盒中去main.json
        var filePath = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)[0]
        filePath = filePath + "/main.json"

        var data = NSData(contentsOfFile: filePath)

        if data == nil {
            // 从bundle中加载数据
            let path = Bundle.main.path(forResource: "main.json", ofType: nil)
            data = NSData(contentsOfFile: path!)
        }
        guard  let array = try? JSONSerialization.jsonObject(with: data! as Data, options: []) as? [[String:Any]] else
        {

                return
        }
        /*
        let array = [
            ["clsName": "WBHomeViewController", "title": "首页", "imageName":"home",
             "visitorInfo": ["imageName":"", "message": "关注一些人，回这里看看有什么惊喜"]
             ],
            ["clsName": "WBMessageViewController", "title": "消息", "imageName":"message_center",
             "visitorInfo": ["imageName":"visitordiscover_image_message", "message": "登录后，别人评论里的微博，发给你的消息，都会在这里收到通知"]
            ],
            ["clsName": "UIViewController"],
            ["clsName": "WBDiscoverViewController", "title": "发现", "imageName":"discover",
             "visitorInfo": ["imageName":"visitordiscover_image_message", "message": "登录后，最新，最热微博尽在掌握，不再会与实时潮流擦肩而过"]
            ],
            ["clsName": "WBProfileViewController", "title": "我", "imageName":"profile",
             "visitorInfo": ["imageName":"visitordiscover_image_profile", "message": "登录后，你的微博、相册、个人资料会显示在这里，展示给别人"]
            ],
        ]

        // 数组 -> 转换成Json 序列化
        let data = try! JSONSerialization.data(withJSONObject: array, options: JSONSerialization.WritingOptions.prettyPrinted)
        (data as NSData).write(toFile: "/Users/admin/Desktop/demo.json", atomically: true)
        */
        // 创建控制器数组
        var arrayM = [UIViewController]()

         // 设置tabbar的子控制器
        for dict in array! {
            arrayM.append(controller(dict: dict))
        }
        viewControllers = arrayM
    }

    /// 使用字典创建一个子控制器
    ///
    /// - Parameter dict: 信息字典[clsName， title， imageName, visitorInfo]
    /// - Returns: 子控制器
    private func controller(dict:[String: Any]) ->UIViewController {

        // 1.取得字典内容
        guard let clsName = dict["clsName"] as? String,
            let title = dict["title"] as? String,
            let imageName = dict["imageName"] as? String,
            let cls = NSClassFromString(Bundle.main.namespace + "." + clsName) as? WBBaseViewController.Type,
            let vicitorDict = dict["visitorInfo"] as? [String:String]

        else {
            return UIViewController()
        }
        let vc = cls.init()
        vc.visitorInfoDictionary = vicitorDict
        vc.title = title
        vc.tabBarItem.image = UIImage(named: "tabbar_" + imageName)
        vc.tabBarItem.selectedImage = UIImage(named: "tabbar_" + imageName + "_selected")?.withRenderingMode(UIImageRenderingMode.alwaysOriginal)

        // 设置tabbar的标题字体颜色
        vc.tabBarItem.setTitleTextAttributes(
            [NSForegroundColorAttributeName: UIColor.orange],
            for: UIControlState.highlighted)
        // 系统默认的是 12 号字体， 要设置mormal的字体大小
        vc.tabBarItem.setTitleTextAttributes(
            [NSFontAttributeName: UIFont.systemFont(ofSize: 12)],
            for: UIControlState.normal)

        /// 实例化导航控制器的时候， 回调用 push 方法将rootVC 压栈
        let nav = WBNavigationController(rootViewController: vc)

        return nav
    }
}
